package com.common.service.impl;

import com.common.model.Result;
import com.common.model.TaskCondition;
import com.common.model.TaskVO;
import com.common.service.TasksService;
import com.gavel.utils.StringUtils;
import com.jd.service.JDShelvesTaskService;
import com.mrobuy.jdvc.dao.CommonDao;
import com.mrobuy.jdvc.entity.Task;
import com.mrobuy.jdvc.entity.VCShelvesTask;
import com.mrobuy.util.IdentifierGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service("tasksService")
public class TasksServiceImpl implements TasksService {

    private static Logger LOG = LoggerFactory.getLogger(JDShelvesTaskService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private CommonDao commonDao;

    @Override
    public Result<TaskVO> loadTasks(TaskCondition condition) {

        Result<TaskVO> result = new Result();

        List<Object> params = new ArrayList<>();

        StringBuilder whereCond = new StringBuilder(" where 1 =1 ");
        if (StringUtils.isNotBlank(condition.getType()) ) {
            whereCond.append("  and TYPE = ? ");
            params.add(condition.getType());
        }

        if (StringUtils.isNotBlank(condition.getFlag()) ) {
            whereCond.append("  and FLAG like ? ");
            params.add("%" + StringUtils.trim(condition.getFlag()) + "%");
        }

        if (StringUtils.isNotBlank(condition.getName()) ) {
            whereCond.append("  and TITLE like ? ");
            params.add("%" + StringUtils.trim(condition.getName()) + "%");
        }

        try {
            String sql = "select * from TASK ";

            String cnt_sql = "select count(1)  from TASK ";

            int count = jdbcTemplate.queryForObject(cnt_sql + whereCond.toString(), params.toArray(new Object[params.size()]), Integer.class);


            int fromIndex = (condition.getPage() - 1)*condition.getLimit();
            int toIndex = condition.getPage()*condition.getLimit();

            if ( fromIndex > count ) {
                fromIndex = 0;
                toIndex = 0;
            } else if ( toIndex > count ) {
                toIndex = count;
            }

            params.add(fromIndex);
            params.add(toIndex);
            List<TaskVO> list = jdbcTemplate.query(sql + whereCond.toString() + " limit ?, ?", params.toArray(new Object[params.size()]), new BeanPropertyRowMapper(TaskVO.class));

            result.setCode(0);
            result.setCount(count);
            result.setData(list);

        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

        return result;
    }

    @Override
    public Result buildShelvesTask(Task task) {

        Result result = new Result();

        try {
            Task exist = jdbcTemplate.queryForObject("select * from  task where ID = ?", new BeanPropertyRowMapper<>(Task.class), task.getId());

            List<VCShelvesTask> vcShelvesTasks = jdbcTemplate.queryForList("select * from  VC_SHELVES_TASK where SOURCE = ?", VCShelvesTask.class, task.getId());
            if ( vcShelvesTasks!=null && vcShelvesTasks.size() > 0 ) {
                result.setCode(0);
                result.setMsg("采集任务[" + task.getTitle() + "]已经有生成了的上架任务!");
                return result;
            }


            VCShelvesTask vcShelvesTask = new VCShelvesTask();
            vcShelvesTask.setId(IdentifierGen.uuid());
            vcShelvesTask.setName(exist.getTitle());
            vcShelvesTask.setRemark(exist.getTypename());

            if ( "success".equalsIgnoreCase(exist.getStatus()) ) {
                vcShelvesTask.setState("2");
            } else {
                vcShelvesTask.setState("1");
            }

            vcShelvesTask.setCreatetime(Calendar.getInstance().getTime());
            vcShelvesTask.setSource(exist.getId());
            vcShelvesTask.setEnable("N");

            commonDao.insert(vcShelvesTask);
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("采集任务[ID: " + task.getId() + "]记录已失效!");
        }

        return result;
    }
}
